/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.spi.ServiceRegistry;

import com.googlecode.opendoclibrary.client.spi.IConnectionFactory;

public class ODLConnectionFactory
{

    private IConnectionFactory cf;

    private final String connectionUrl;

    private String password;

    private Map<String, IConnectionFactory> registeredFactories;

    private String username;

    public ODLConnectionFactory( String connectionUrl )
    {
        this.connectionUrl = connectionUrl;
        if ( connectionUrl == null )
        {
            throw new IllegalArgumentException( "connectionUrl may not be null" );
        }

        int split = connectionUrl.indexOf( ':' );

        if ( split <= 0 )
        {
            throw new IllegalArgumentException( "missing protocol in connectionUrl" );
        }

        String protocol = connectionUrl.substring( 0, split );

        cf = getRegisteredFactories().get( protocol );

    }

    public IODLConnection createConnection() throws AuthenticationFailedException
    {
        return cf.createConnection( username, password, connectionUrl );
    }

    private synchronized Map<String, IConnectionFactory> getRegisteredFactories()
    {
        if ( registeredFactories == null )
        {
            registeredFactories = new HashMap<String, IConnectionFactory>();

            Iterator<IConnectionFactory> providers = ServiceRegistry.lookupProviders( IConnectionFactory.class );

            while ( providers.hasNext() )
            {
                IConnectionFactory cf = providers.next();
                registeredFactories.put( cf.getHandledProtocol(), cf );
            }
        }
        return registeredFactories;
    }

    public void setPassword( String password )
    {
        this.password = password;
    }

    public void setUsername( String username )
    {
        this.username = username;
    }
}
